from django import template
from django.db.models.aggregates import Count
from article.models import Article, Category, Tag
from blog.models import FriendLink
from django.db.models.functions import ExtractYear,ExtractMonth

register = template.Library()


@register.inclusion_tag('inclusions_tags/tags/recent_articles.html', takes_context=True)
def show_recent_posts(context, num=5):
    return {
        'recent_post_list': Article.objects.all().order_by('-created_time')[:num],
    }

'''
takes_context 设置为 True 时将告诉 django，在渲染 recent_articles.html 模板时，不仅传入show_recent_posts 返回的模板变量，
同时会传入父模板（即使用 {% show_recent_posts %} 模板标签的模板）
上下文（可以简单理解为渲染父模板的视图函数传入父模板的模板变量以及 django 自己传入的模板变量）
'''

@register.inclusion_tag('inclusions_tags/tags/archives.html', takes_context=True)
def show_archives(context):
    date_list = Article.objects.annotate(year=ExtractYear('created_time'),month=ExtractMonth('created_time')).\
        values('year','month').order_by('year','month').annotate(num_articles=Count('category'))
    return {
        # 'date_list': Article.objects.dates('created_time', 'month', order='DESC'),
        'date_list': date_list,
    }


@register.inclusion_tag('inclusions_tags/tags/categories.html', takes_context=True)
def show_categories(context):
    category_list = Category.objects.annotate(num_articles=Count('article')).filter(num_articles__gt=0)
    return {
        'category_list': category_list,
    }

@register.inclusion_tag('inclusions_tags/tags/tags.html', takes_context=True)
def show_tags(context):
    tag_list = Tag.objects.annotate(num_articles=Count('article')).filter(num_articles__gt=0)
    return {
        'tag_list': tag_list,
    }

@register.inclusion_tag('inclusions_tags/tags/frendly.html',takes_context=True)
def show_frendly(context,num=5):
    # frends_list = FriendLink.objects.filter(is_show=True).order_by('created_time')[:num],
    frends_list = FriendLink.objects.all()
    return {
        "friends_list":frends_list,
    }